package com.zengqingfa.springboot.redis.service;

import com.alibaba.fastjson.JSON;
import com.zengqingfa.springboot.redis.dto.UserInfo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @fileName: RedisService
 * @author: zengqf3
 * @date: 2021-3-5 10:25
 * @description:
 */
@Service
public class RedisService implements RedisServiceInterface {

    public static final Map<String, String> map = new HashMap<>();

    static {
        map.put("k1", JSON.toJSONString(new UserInfo("k1", "v1")));
        map.put("k2", JSON.toJSONString(new UserInfo("k2", "v2")));
        map.put("k3", JSON.toJSONString(new UserInfo("k3", "v3")));
        map.put("k4", JSON.toJSONString(new UserInfo("k4", "v4")));
    }

    @Override
    public Map<String, String> getList() {
        return map;
    }

    /**
     * unless 排除result==null的情况，其他情况都缓存
     *
     * @param userInfo
     * @return
     */
    @Override
    @Cacheable(cacheNames = "cacheTest", key = "#a0.key", unless = "#result==null")
    public String add(UserInfo userInfo) {
        String add = map.put(userInfo.getKey(),JSON.toJSONString(userInfo));
        return add;
    }

    /**
     * 清除缓存
     *
     * @param key
     * @return
     */
    @Override
    @CacheEvict(cacheNames = "cacheTest", key = "#a0", condition = "#result != null")
    public String delete(String key) {
        String remove = map.remove(key);
        return remove;
    }


    @Override
    @CachePut(cacheNames = "cacheTest", key = "#a0.key")
    public String update(UserInfo userInfo) {
        String update = map.put(userInfo.getKey(), JSON.toJSONString(userInfo));
        return update;
    }

    @Cacheable(cacheNames = "cacheTest", key = "#a0", unless = "#result==null")
    @Override
    public String getByKey(String key) {
        return map.get(key);
    }


}
